<?php
namespace app\api\controller;
use think\Controller;
use think\Cookie;
use think\Db;

class Lywqautotrigger extends Base
{

    public function __construct()
    {
        parent::__construct();
    }

    
    // 发送请求
    protected function sendReq($url)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,  $url);
        // //声明使用POST方式来进行发送
        // curl_setopt($ch, CURLOPT_POST, 1);
        //设定请求后返回结果
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        //忽略证书(目标服务器的接口有https证书时使用)
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        //忽略header头信息
        curl_setopt($ch, CURLOPT_HEADER, 0);
        //设置超时时间,0无限等待
        curl_setopt($ch, CURLOPT_TIMEOUT, 0);
        $url = curl_exec($ch);
        curl_close($ch);
        // $str = json_decode($url, true);
        return $url;
    }


    // 时间间隔判断
    protected function timeRun($runtime,$interval)
    {
        $time = date('Y-m-d H:i:s');
        $hour = (strtotime($time)-strtotime($runtime))%86400/3600;
        if ($hour>=$interval) {
            return 'true';
        }else{
            return 'false';
        }
    }


    // 校验管理员
    protected function check_admin($admin_id,$admin_name,$admin_check)
    {   
        // if(empty($admin_id) || empty($admin_name) || empty($admin_check)){
        //     return 'false';
        // }

        // $where = [];
        // $where['admin_id'] = $admin_id;
        // $where['admin_name'] = $admin_name;
        // $where['admin_status'] =1 ;

        // $info = Db::table('mac_admin')->where($where)->find();
        // if(empty($info)){
        //     return 'false';
        // }

        // $login_check = md5($info['admin_random'] . $info['admin_name'] .$info['admin_id']) ;
        // if($login_check != $admin_check){
        //     return 'false';
        // }
        return 'true';
    }


    // 初始化
    public function initialize()
    {
        $param = input();
        $admin_id = $param['admin_id']==''?$_COOKIE["admin_id"]:$param['admin_id'];
        $admin_name = $param['admin_name']==''?$_COOKIE["admin_name"]:$param['admin_name'];
        $admin_check = $param['admin_check']==''?$_COOKIE["admin_check"]:$param['admin_check'];
        $res = $this->check_admin($admin_id,$admin_name,$admin_check);
        if ($res == 'true') {
            $tableName = 'lywq_autotrigger';
            $isTable = db()->query('SHOW TABLES LIKE '."'".$tableName."'");
            if(!$isTable){
                $sql = "CREATE TABLE `lywq_autotrigger` (
                  `id` int(11) NOT NULL AUTO_INCREMENT,
                  `name` varchar(255) DEFAULT NULL COMMENT '名称',
                  `describe` varchar(255) DEFAULT NULL COMMENT '描述',
                  `url` varchar(255) DEFAULT NULL COMMENT '访问链接',
                  `status` int(1) DEFAULT '0' COMMENT '状态(1为开启，0为关闭)',
                  `runtime` datetime DEFAULT NULL COMMENT '运行时间',
                  `interval` int(2) DEFAULT '24' COMMENT '时间间隔',
                  PRIMARY KEY (`id`)
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8;";
                 $zxjg = db()->query($sql);
                 $isTable = db()->query('SHOW TABLES LIKE '."'".$tableName."'");
                 if($isTable){
                    // 数据库创建成功
                    $tableName = 'lywq_autotrigger_log';
                    $isTable = db()->query('SHOW TABLES LIKE '."'".$tableName."'");
                    if (!$isTable) {
                        $sql = "CREATE TABLE `lywq_autotrigger_log` (
                          `id` int(11) NOT NULL AUTO_INCREMENT,
                          `name` varchar(255) DEFAULT NULL COMMENT '名称',
                          `rwid` varchar(255) DEFAULT NULL COMMENT '任务id',
                          `describe` varchar(255) DEFAULT NULL COMMENT '描述',
                          `url` varchar(255) DEFAULT NULL COMMENT '访问链接',
                          `runtime` datetime DEFAULT NULL COMMENT '运行时间',
                          PRIMARY KEY (`id`)
                        ) ENGINE=InnoDB DEFAULT CHARSET=utf8;";
                         $zxjg = db()->query($sql);
                         $isTable = db()->query('SHOW TABLES LIKE '."'".$tableName."'");
                         if ($isTable) {
                            return 1;
                         } else {
                             // 数据库创建失败
                             return 2;
                         }
                    } else {
                        // 数据库已创建
                        return 0;
                    }
                    return 1;
                 }else {
                     // 数据库创建失败
                     return 2;
                 }
            } else{
                // 数据库已创建
                return 0;
            }
        } else{
            return '非法请求！';
        }
    }


    // 首页
    public function index()
    {
        $param = input();
        $admin_id = $param['admin_id']==''?$_COOKIE["admin_id"]:$param['admin_id'];
        $admin_name = $param['admin_name']==''?$_COOKIE["admin_name"]:$param['admin_name'];
        $admin_check = $param['admin_check']==''?$_COOKIE["admin_check"]:$param['admin_check'];
        $res = $this->check_admin($admin_id,$admin_name,$admin_check);
        if ($res == 'true') {
            $page=$param['page'];
            $limit=$param['limit'];
            if($page=='' or $page <=1){
                $page=0;
            }else{
                $page=($page-1)*$limit;
            }
            if($limit=='' or $limit <=1){
                $limit=6;
            }
            
            $this->assign('page',$param['page']);
            $this->assign('limit',$param['limit']);
            
            $sql = "SELECT * FROM lywq_autotrigger LIMIT ".$page.",".$limit;
            $list = db()->query($sql);
            $sql = "SELECT COUNT(*) FROM lywq_autotrigger ";
            $jg = db()->query($sql);
            $count = $jg[0]['COUNT(*)'];
            $this->assign('list',$list);
            $this->assign('title','任务列表');
            $this->assign('count',$count);
            return $this->fetch('admin@lywq/Autotrigger/html/index'); 
        } else{
            return '非法请求！';
        }
    }
    
    
    // 日志
    public function log()
    {
        $param = input();
        $admin_id = $param['admin_id']==''?$_COOKIE["admin_id"]:$param['admin_id'];
        $admin_name = $param['admin_name']==''?$_COOKIE["admin_name"]:$param['admin_name'];
        $admin_check = $param['admin_check']==''?$_COOKIE["admin_check"]:$param['admin_check'];
        $res = $this->check_admin($admin_id,$admin_name,$admin_check);
        if ($res == 'true') {
            $page=$param['page'];
            $limit=$param['limit'];
            if($page=='' or $page <=1){
                $page=0;
            }else{
                $page=($page-1)*$limit;
            }
            if($limit=='' or $limit <=1){
                $limit=6;
            }
            
            $this->assign('page',$param['page']);
            $this->assign('limit',$param['limit']);
            
            $sql = "SELECT * FROM lywq_autotrigger_log ";
            
            $where = ' WHERE 1=1 ';
            if(!empty($param['wd'])){
                $this->assign('wd',$param['wd']);
                $where = $where." AND name LIKE '%".$param['wd']."%' ";
            }
            if(!empty($param['kstime']) && !empty($param['jstime'])){
                $this->assign('kstime',$param['kstime']);
                $this->assign('jstime',$param['jstime']);
                $where = $where." AND runtime >= '".$param['kstime'].' 00:00:00'."' AND runtime <= '".$param['jstime']." 23:59:59'";
            }
            
            $sql = $sql.$where." LIMIT ".$page.",".$limit;
            $list = db()->query($sql);
            
            $sql = "SELECT COUNT(*) FROM lywq_autotrigger_log ";
            $sql = $sql.$where;
            $jg = db()->query($sql);
            $count = $jg[0]['COUNT(*)'];
            $this->assign('list',$list);
            $this->assign('title','日志列表');
            $this->assign('count',$count);
            return $this->fetch('admin@lywq/Autotrigger/html/log'); 
        } else{
            return '非法请求！';
        }
    }
    

    // 是否初始化
    public function ischushihua()
    {
        $param = input();
        $admin_id = $param['admin_id']==''?$_COOKIE["admin_id"]:$param['admin_id'];
        $admin_name = $param['admin_name']==''?$_COOKIE["admin_name"]:$param['admin_name'];
        $admin_check = $param['admin_check']==''?$_COOKIE["admin_check"]:$param['admin_check'];
        $res = $this->check_admin($admin_id,$admin_name,$admin_check);
        if ($res == 'true') {
           $tableName = 'lywq_autotrigger';
           $isTable = db()->query('SHOW TABLES LIKE '."'".$tableName."'");
           if($isTable){
               $tableName = 'lywq_autotrigger_log';
               $isTable = db()->query('SHOW TABLES LIKE '."'".$tableName."'");
               if ($isTable) {
    	           return 'true';
               }
        	   return 'false';
           }
        	return 'false';
        } else{
            return '非法请求！';
        }
    }


    // 任务管理
    public function info()
    {
        $param = input();
        $admin_id = $param['admin_id']==''?$_COOKIE["admin_id"]:$param['admin_id'];
        $admin_name = $param['admin_name']==''?$_COOKIE["admin_name"]:$param['admin_name'];
        $admin_check = $param['admin_check']==''?$_COOKIE["admin_check"]:$param['admin_check'];
        $res = $this->check_admin($admin_id,$admin_name,$admin_check);
        if ($res == 'true') {
            $sql = "SELECT * FROM lywq_autotrigger";
            $list = db()->query($sql);
            if (Request()->isPost()) {
                $id = input('id');
                $name = input('name');
                $status = input('status');
                $describe = input('describe');
                $interval = input('interval')==''?24:input('interval');
                $url = input('url');
                if ($id=='') {
                    $res = Db::table('lywq_autotrigger')->insert(['name' => $name,'status' => $status,'describe' => $describe,'interval' => $interval,'url' => $url]);
                } else {
                    $res = Db::table('lywq_autotrigger')->where('id', $id)->update(['name' => $name,'status' => $status,'describe' => $describe,'interval' => $interval,'url' => $url]);
                }
                if($res!=1){
                    return $this->error('保存配置文件失败，请重试!');
                }
                return $this->success('保存成功!');
            }
            $id = input('id');
            $where = [];
            $where['id'] = $id;
            $info = Db::table('lywq_autotrigger')->where($where)->find();
            $this->assign('info',$info);
            $this->assign('title','任务管理');
            return $this->fetch('admin@lywq/Autotrigger/html/info');
        } else{
            return '非法请求！';
        }
    }
    
    
    // 删除任务
    public function del()
    {
        $param = input();
        $admin_id = $param['admin_id']==''?$_COOKIE["admin_id"]:$param['admin_id'];
        $admin_name = $param['admin_name']==''?$_COOKIE["admin_name"]:$param['admin_name'];
        $admin_check = $param['admin_check']==''?$_COOKIE["admin_check"]:$param['admin_check'];
        $res = $this->check_admin($admin_id,$admin_name,$admin_check);
        if ($res == 'true') {
            $id = input('id');
            if ($id!='') {
                $where = [];
                $where['id'] = $id;
                $res = Db::table('lywq_autotrigger')->where($where)->delete();
                if($res!=1){
                    return $this->error('删除失败，请重试!');
                }
                return $this->success('删除成功!'); 
            } else {
                // $where = [];
                // $where['id'] = ['gt',0];
                // $res = Db::table('lywq_autotrigger')->where($where)->delete();
                $res = db()->execute('TRUNCATE lywq_autotrigger;');
                if($res!=0){
                    return $this->error('清空失败，请重试!');
                }
                return $this->success('清空成功!'); 
            }
        } else{
            return '非法请求！';
        }
    }
    
    
    // 任务状态
    public function field()
    {
        $param = input();
        $admin_id = $param['admin_id']==''?$_COOKIE["admin_id"]:$param['admin_id'];
        $admin_name = $param['admin_name']==''?$_COOKIE["admin_name"]:$param['admin_name'];
        $admin_check = $param['admin_check']==''?$_COOKIE["admin_check"]:$param['admin_check'];
        $res = $this->check_admin($admin_id,$admin_name,$admin_check);
        if ($res == 'true') {
            $id = $param['ids'];
            $col = $param['col'];
            $status = $param['val'];
    
            if(!empty($id) && in_array($col,['status'])){
                $where = [];
                $where['id'] = $id;
                $res = Db::table('lywq_autotrigger')->where($where)->update(['status' => $status]);
                if($res!=1){
                    return $this->error('保存失败，请重试!');
                }
                return $this->success('保存成功!');
            }
            return $this->error('参数错误');            
        } else{
            return '非法请求！';
        }
    }
    
    
    // 执行任务
    public function execute()
    {
        $param = input();
        require('./addons/Autotrigger/config/config.php');
        $type = $lywq['Autotrigger']['type'];
        $tok = $lywq['Autotrigger']['token'];
        $token = $param['token'];
        $mode = $param['mode'];
        $execute = false;
        if ($type==0) {
            return '接口已关闭！';
        }
        if ($type!=0) {
            if ($mode=='test') {
                $id = $param['id'];
                $where = [];
                $where['id'] = $id;
                $info = Db::table('lywq_autotrigger')->where($where)->find();
                if ($info['status']==0) {
                    return '任务未开启！';
                }
                $execute = true;
            } elseif ($mode=='formal') {
                if ($type==1) {
                    $execute = true;
                } else {
                    return '非法请求！';
                }
            }
        }
        
        if (($token==$tok && $type==2) || $execute) {
            $sql = "SELECT * FROM lywq_autotrigger WHERE status = 1 ";
            if ($id!='') {
                $sql = $sql.' AND id = '.$id;
            }
            $list = db()->query($sql);
            
            for($i=0;$i<count($list);$i++){
                $id = $list[$i]['id'];
                $runtime = $list[$i]['runtime'];
                $interval = $list[$i]['interval'];
                $name = $list[$i]['name'];
                $url = $list[$i]['url'];
                $time = date('Y-m-d H:i:s');
                $tag = $this->timeRun($runtime,$interval);
                $write = false;
                if ($tag=='true') {
                    $res = $this->sendReq($url);
                    if ($res!='') {
                        Db::table('lywq_autotrigger')->where('id', $id)->update(['runtime' => $time]);
                        $msg = $res;
                        $write = true;
                    } else {
                        $msg = '请求失败！';
                        $write = true;
                    }
                } else {
                    $msg = '时间间隔小于配置间隔时间，不执行！';
                    $write = false;
                }
                if ($write) {
                    $res = Db::table('lywq_autotrigger_log')->insert(['name' => $name,'rwid' => $id,'describe' => $msg,'runtime' => $time,'url' => $url]);
                } else {
                    $where = [];
                    $where['rwid'] = $id;
                    $where['describe'] = $msg;
                    $info = Db::table('lywq_autotrigger_log')->where($where)->find();
                    if ($info['id']!='') {
                        Db::table('lywq_autotrigger_log')->where('id', $info['id'])->update(['runtime' => $time,'describe' => $msg]);
                    } else {
                        $res = Db::table('lywq_autotrigger_log')->insert(['name' => $name,'rwid' => $id,'describe' => $msg,'runtime' => $time,'url' => $url]);
                    }
                }
                
                echo $msg.'<br>';
            }
            return ;

        } else{
            return '非法请求！';
        }
    }
    
    
    // 删除日志
    public function dellog()
    {
        $param = input();
        $admin_id = $param['admin_id']==''?$_COOKIE["admin_id"]:$param['admin_id'];
        $admin_name = $param['admin_name']==''?$_COOKIE["admin_name"]:$param['admin_name'];
        $admin_check = $param['admin_check']==''?$_COOKIE["admin_check"]:$param['admin_check'];
        $res = $this->check_admin($admin_id,$admin_name,$admin_check);
        if ($res == 'true') {
            $id = input('id');
            if ($id!='') {
                $where = [];
                $where['id'] = $id;
                $res = Db::table('lywq_autotrigger_log')->where($where)->delete();
                if($res!=1){
                    return $this->error('删除失败，请重试!');
                }
                return $this->success('删除成功!'); 
            } else {
                // $where = [];
                // $where['id'] = ['gt',0];
                // $res = Db::table('lywq_autotrigger_log')->where($where)->delete();
                $res = db()->execute('TRUNCATE lywq_autotrigger_log;');
                if($res!=0){
                    return $this->error('清空失败，请重试!');
                }
                return $this->success('清空成功!'); 
            }
        } else{
            return '非法请求！';
        }
    }
    
}